package com.xoa.plugin.archives.ct.oaws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xoa.dao.work.WorkMapper;
import com.xoa.global.proxy.TriggerSubject;
import com.xoa.model.archive.DocArchive;
import com.xoa.model.nccloud.NCCInterfaceLog;
import com.xoa.model.nccloud.NccPsninfo;
import com.xoa.model.users.Users;
import com.xoa.model.workflow.TriggerPlugIn;
import com.xoa.service.archive.ArchWebServiceImplService;
import com.xoa.service.archive.FileUploadService;
import com.xoa.service.archive.impl.ArchWebServiceImpl;
import com.xoa.service.nccloud.INCCInterFaceLogService;
import com.xoa.service.nccloud.INCCPsndocService;
import com.xoa.service.nccloud.INCCloudService;
import com.xoa.util.CookiesUtil;
import com.xoa.util.DateUtil;
import com.xoa.util.ToJson;
import com.xoa.util.archive.CommonUtils;
import com.xoa.util.archive.HttpUploadFile;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.common.wrapper.BaseWrapper;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.xml.namespace.QName;
import java.io.File;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 行政发文
 */
@Service
public class WorkFlowAdministrativeTrigger{

    /*
    接口工具
     */


    //表数据
    private TriggerPlugIn tri = null;
    @Autowired
    INCCInterFaceLogService logService;

    @Autowired
    INCCPsndocService psndocService;


    @Autowired
    private FileUploadService fileUploadService;
    //人员对象
    private Users sessionInfo=null;


    public ToJson doRun(TriggerPlugIn tri, HttpServletRequest httpServletRequest)throws Exception {



            this.tri =tri;
            //当前表单id
            String run_id = tri.getRunId();
            //表id
            String tableName = tri.getFlowId();
            ToJson toJson=new ToJson();
        try{
            //获取当前账户信息
            Cookie redisSessionCookie = CookiesUtil.getCookieByName(httpServletRequest, "redisSessionId");
            sessionInfo = SessionUtils.getSessionInfo(httpServletRequest.getSession(), Users.class, new Users(), redisSessionCookie);

            URL url = new URL("http://106.13.80.96:8060/Webservice/Collect/archivesV4?wsdl");
            QName qName = new QName("http://127.0.0.1/Webservice/Collect/archivesV4", "ArchWebServiceImplService");
            ArchWebServiceImplService archWebServiceImplService = new ArchWebServiceImplService(url,qName);
            ArchWebServiceImpl archWebServiceImpl = archWebServiceImplService.getArchWebServiceImplPort();
            String result = archWebServiceImpl.receiveDocArchive(this.onversioncDto(tri.getModify(),run_id));
            JSONObject jsonObject1=JSON.parseObject(result);
            if(jsonObject1.getInteger("Code")==0){
                toJson.setFlag(0);
            }else{
                throw new RuntimeException(result);

            }
        }catch (Exception e){
            toJson.setFlag(1);
            toJson.setMsg(e.getMessage());

        }
        return toJson;
    }

    /**
     * 表单数据拼接json
     *
     * @param formdata
     * @param runId
     * @return
     * @throws Exception
     */

    public DocArchive onversioncDto(String formdata, String runId) throws Exception {

        //将表单数据json数组解析List<Map<String, Object>>
        JSONArray jsonArrayArchives=new JSONArray();
        List<Map<String, Object>> data = JSONArray.parseObject(formdata, List.class);


        DocArchive docArchive = new DocArchive();


        for (Map<String, Object> datum : data) {
            switch (datum.get("key").toString()) {

                case "DATA_176"://标题
                    docArchive.setTitle(datum.get("value").toString());//合同名称
                    break;
                case "DATA_111"://行文版式

                    break;
                case "DATA_197"://发文字号

                    break;
                case "DATA_210"://发文字号

                    break;
                case "DATA_205"://发文字号

                    break;
                case "DATA_58"://拟 稿 人

                    break;
                case "DATA_157"://拟稿部门

                    break;
                case "DATA_189"://拟稿时间

                    break;
                case "DATA_118"://打  印
                    break;
                case "DATA_187"://期  限
                    break;
                case "DATA_207"://主送内部单位
                    break;
                case "DATA_107"://主送外部单位
                    break;
                case "DATA_173"://抄  送
                    break;
                case "DATA_166"://附  件
                    if(null!=datum.get("value").toString()&&!datum.get("value").toString().equals("")){


                    //附件上传
                    ToJson toJson = fileUploadService.fileUploadFW(datum.get("value").toString());
                    if(!toJson.isFlag()){
                        throw  new RuntimeException(toJson.getMsg());
                    }
                    jsonArrayArchives=(JSONArray)toJson.getData();
                    }
                    break;
            }
        }

        //表单数据
        //调用客户端提交数据
        docArchive.setAppid("oaws");//调用系统
        docArchive.setApptoken("1573611620235600517");//校验代码
        docArchive.setCompanycode("0232");//单位编码
        //档案信息
        docArchive.setRid(runId);//主键
        docArchive.setPid("0");//默认0 关联父主键
        docArchive.setOwner(sessionInfo.getUserId());//隶属人id
        docArchive.setFondsname("福州城市建设投资集团有限公司");//全宗名称
        docArchive.setArchcode(null);//文件档号
        docArchive.setDoccode(null);//件号

        docArchive.setDocnumber("CTXZFW"+new Date().getYear()+(new Date().getMonth()+1)+new Date().getDate()+runId);//合同编号
        docArchive.setAuthor(sessionInfo.getUserName());//责任者
        docArchive.setDocdate(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));//日期
        docArchive.setYear(new SimpleDateFormat("yyyy").format(new Date()));//年度
        docArchive.setRetentionperiod(null);//保管期限
        docArchive.setSecurity(null);//密级
        docArchive.setSecuritytime(null);//保密年限
        docArchive.setPagenum("1");//页数
        docArchive.setDepartment(null);//隶属（归档）部门名称
        docArchive.setDepartmentid(null);//隶属（归档）部门代码
        docArchive.setDepartmentsn(null);//隶属（归档）部门代字
        docArchive.setSection(null);//隶属（归档）
        docArchive.setSectionid(null);//隶属（归档）处室代码
        docArchive.setCreater(sessionInfo.getUserId());//创建（归档）人id
        docArchive.setCreatername(sessionInfo.getUserName());//创建（归档）人姓名
        docArchive.setCreatetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));//创建（归档）时间
        docArchive.setSubject(tri.getSubject());//主题词
        docArchive.setMemo(null);//备注
        docArchive.setRelatearchives(null);//关联公文
        docArchive.setKnownscope(null);//知悉范围
        docArchive.setRelatepersons(null);//知悉人（多个人员id）
        docArchive.setRelatedepartments(null);//知悉部门（多个部门ID）
//匹配路径 具体格式可参照：ArchiveUtils.getServerAttachment
        //name：附件标题，ext：扩展名，file：存储路径 + 实际存储名称。注：路径内不含 oaws 和 owht
        String attachment = jsonArrayArchives.toJSONString();
        docArchive.setAttachment(attachment);//电子文件信息
        docArchive.setExt1(null);//主办部门
        docArchive.setExt2(null);//合作方
        docArchive.setExt3(null);//签约人
        docArchive.setExt4(null);
        docArchive.setExt5(null);
        docArchive.setExt6(null);
        docArchive.setExt7(null);
        docArchive.setExt8(null);
        docArchive.setExt9(null);
        docArchive.setExt10(null);
        docArchive.setExt11(null);
        docArchive.setExt12(null);
        docArchive.setExt13(null);
        docArchive.setExt14(null);
        docArchive.setExt15(null);
        docArchive.setExt16(null);
        docArchive.setExt17(null);
        docArchive.setExt18(null);
        docArchive.setExt19(null);
        docArchive.setExt20(null);
        return docArchive;
    }





    /**
     * 日志保存
     * @param pk
     * @param reqeustBody
     * @param name
     * @param result
     * @throws Exception
     */
    private void saveLog(String pk,String reqeustBody,String name,String result,String state)throws Exception{
        NCCInterfaceLog ncclog = new NCCInterfaceLog();
        ncclog.setBusinessNo(pk);
        ncclog.setContent(reqeustBody);
        ncclog.setName(name);
        ncclog.setResult(result);
        ncclog.setState(state);
        ncclog.setDisposeState("0");
        logService.save(ncclog);
    }



}

